<template>
  <div class="map">
    <div id="map" :style="{ height: maxHeight }"></div>

    <div
      style="
        background: #fff;
        position: fixed;
        right: 0;
        top: 100px;
        padding: 0 3px;
        z-index: 2;
      "
    >
      <ul>
        <li
          class="cursor-pointer"
          @click="handleControl('restore')"
          style="padding: 0 5px"
        >
          <div style="border-bottom: 1px solid #d3d3d3; padding-top: 10px">
            <i class="el-icon-refresh-left" size="16"></i>
          </div>
        </li>
        <li
          class="cursor-pointer"
          @click="handleControl('enlarge')"
          style="padding: 0 5px"
        >
          <div style="border-bottom: 1px solid #d3d3d3; padding-top: 10px">
            <i class="el-icon-plus" size="16"></i>
          </div>
        </li>
        <li
          class="cursor-pointer"
          @click="handleControl('norrow')"
          style="padding: 0 5px"
        >
          <div style="border-bottom: 1px solid #d3d3d3; padding-top: 10px">
            <i class="el-icon-minus" size="16"></i>
          </div>
        </li>
        <li>
          <div
            style="
              background: #fff;
              position: fixed;
              right: 0;
              bottom: 10px;
              z-index: 2;
            "
          ></div>
        </li>
      </ul>
      <!-- 公告 -->
      <!-- <div class="notice">
        <notification/>
      </div> -->
    </div>
    <!-- 弹窗显示当前站点所有线路信息     v-if="isShowRouteList && isCollecData"-->
    <route-list
      :collectDatas="collectDatas"
      :routeName="routeName"
      :isCloseBtn="true"
      :isBackBtn="true"
      @handleChangeRoute="handleChangeRoute"
      @handleClose="handleClose"
    />
    <div
      style="position: fixed; bottom: 0; right: 0; z-index: 999"
      @click="handleShowNotify"
      v-if="isNotifyShow"
    >
      <img @click="getMessageinfos" src="@/assets/images/notice.png" alt="" />
    </div>
  </div>
</template>
<script>
import { getAllSite } from "@/api/collect";
import { getStationRoute, getMessageinfos } from "@/api/collect";
import routeList from "@/components/routeList";
import notification from "@/components/notification";
import { mapState } from "vuex";
import { Notification } from "element-ui";
import { getRefreshTime } from "@/utils/location";
import CircleStyle from "ol/style/Circle";
import { Fill, Icon, Stroke, Style, Text } from "ol/style";
export default {
  components: {
    routeList,
    notification,
  },
  data() {
    return {
      // 服务器下发数据的话，需要进行watch监听
      collectDatas: [], //线路列表
      isShowRouteList: false, //是否显示线路弹窗
      routeName: "", //车站名称
      routeRundirection: "", //线路运行方向
      maxHeight: "", //可视区高度
      isCollecData: false,
      dualserialid: "",
      inputBusroute: "",
      setTime: null,
      refreshTime: null,
      getPredictList: [],
      isNotify: "",
      markers: [],
    };
  },
  computed: {
    ...mapState(["lnglat", "changeRefresh", "changeWebsite", "isNotifyShow"]),
  },
  watch: {
    lnglat() {
      this.handleRestore();
    },
    changeRefresh() {
      this.getRefreshTime();
      this.getStationRoute();
    },
    changeWebsite() {},
  },
  created() {
    if (!this.isNotifyShow) {
      this.getMessageinfos();
    }
  },

  mounted() {
    let maxHeight =
      window.innerHeight ||
      document.documentElement.clientHeight ||
      document.body.clientHeight;
    this.maxHeight = maxHeight + "px";
    this.initMap();
    // 获取所有站点
    this.refreshTime = getRefreshTime(this.$store.state.changeRefresh);
  },
  methods: {
    handleShowNotify() {
      this.getMessageinfos();
    },
    // 获取通告信息
    async getMessageinfos() {
      let that = this;
      that.$store.commit("setIsNotifyShow", false);
      this.isNotify = "";
      Notification.closeAll();
      let date = this.$dayjs(new Date().getTime()).format(
        "YYYY-MM-DD hh:mm:ss"
      );
      let params = {
        time: date,
        type: '1'
      };
      let { status, data } = await getMessageinfos(params);
      if (status == 200) {
        // let message = [""];
        // data.forEach((item) => {
        //   message.push(item.content)
        // });
        // const h = this.$createElement;
        let dom;
        data.forEach(e => {
          if(dom){
            dom += `<div>${this.$t('langName.langName102')+':'+e.routeid+','+this.$t('langName.langName145')+':'}${e.content}</div>`
          }else{
            dom = `<div>${this.$t('langName.langName102')+':'+e.routeid+','+this.$t('langName.langName145')+':'}${e.content}</div>`
          }    
        })
        this.isNotify = this.$notify({
          title: this.$t("langName.langName104"),
          message: dom,
          // message: h(
          //   data.forEach((item) => {
          //     message.push(item.content + "\n")
          //     "div",
          //   {
          //     style:
          //       "height:300px;background:#fff;overflow:auto;border:1px solid #fff;",
          //     class: "notify-success",
          //   },
          //   messsage
          //   })
          // ),
          position: "bottom-right",
          duration: 0,
          dangerouslyUseHTMLString: true,
          onClose: function () {
            that.$store.commit("setIsNotifyShow", true);
          },
        });
      }
    },
    // 获取全部站点
    async getAllSite(minLng, maxLng, minLat, maxLat) {
      let params = {
        minLng: minLng,
        maxLng: maxLng,
        minLat: minLat,
        maxLat: maxLat,
        size: 100,
      };

      let { status, data } = await getAllSite(params);
      if (status == 200) {
        this.siteLists = data;
        this.drawSpot();
      }
    },
    // 刷新全部站点
    async handleRefreshStation() {
      let { status, data } = await getAllSite();
      if (status == 200) {
        this.siteLists = data;
        sessionStorage.setItem(
          "allStationLists",
          JSON.stringify(this.siteLists)
        );
      }
    },
    // 复原地图
    handleRestore() {
      if (this.map) {
        console.log("复原地图", this.$store.state.lnglat[1]);
        const origin = {
          lat: this.$store.state.lnglat[1],
          lng: this.$store.state.lnglat[0],
        };
        this.map.setCenter(origin);
        this.map.setZoom(window.MAPSETTINGS.DEFAULTZOOM);

        // this.map.getView().animate({
        //   center: this.$store.state.lnglat,
        //   // center: [120.14727,35.984278],
        //   zoom: window.MAPSETTINGS.DEFAULTZOOM,
        // });
      }
    },
    // 绘制地图
    initMap() {
      const origin = {
        lat: this.$store.state.lnglat[1],
        lng: this.$store.state.lnglat[0],
      };
      this.map = new google.maps.Map(document.getElementById("map"), {
        zoom: window.MAPSETTINGS.DEFAULTZOOM,
        center: origin,
        zoomControl: false,
        mapTypeId: "roadmap",
        streetViewControl: false,
        fullscreenControl: false,
        mapTypeControl: false,
      });
      setTimeout(() => {
        const bounds = this.map.getBounds();
        console.log("经纬度范围", bounds);
        let minLng = bounds.getNorthEast().lng();
        let maxLng = bounds.getSouthWest().lng();
        let minLat = bounds.getNorthEast().lat();
        let maxLat = bounds.getSouthWest().lat();
        this.getAllSite(minLng, maxLng, minLat, maxLat);
      }, 1000);
      this.map.addListener("center_changed", () => {
        console.log("中心点更改");
        this.markers.forEach((item) => {
          item.setMap(null);
        });
        const bounds = this.map.getBounds();
        // let minLng = bounds.Lh.lo;
        // let maxLng = bounds.Lh.hi;
        // let minLat = bounds.ci.lo;
        // let maxLat = bounds.ci.hi;
        let minLng = bounds.getNorthEast().lng();
        let maxLng = bounds.getSouthWest().lng();
        let minLat = bounds.getNorthEast().lat();
        let maxLat = bounds.getSouthWest().lat();
        this.getAllSite(minLng, maxLng, minLat, maxLat);
      });
    },
    // 绘制站点
    drawSpot() {
      new google.maps.Marker({
        position: new google.maps.LatLng(
          this.$store.state.lnglat[1],
          this.$store.state.lnglat[0]
        ),
        icon: {
          url: require("../assets/images/mapAddress.png"),
          scaledSize: new google.maps.Size(30, 35),
        },
        map: this.map,
      });
      let imageStyle = new CircleStyle({
        radius: 6,
        fill: new Fill({
          color: "#000000"
        }),
        stroke: new Stroke({ color: 'white', width: 0 })
      });
      var greenCircle = {
        // path: 'M 125,5 155,90 245,90 175,145 200,230 125,180 50,230 75,145 5,90 95,90 z', 
        path: 'M 100,100 m -75, 0 a 75,75 0 1,0 150,0 a 75,75 0 1,0 -150,0',
        fillColor: 'white', 
        fillOpacity: 0.3, 
        scale: 0.1, 
        strokeColor: 'green',
        strokeWeight: 3
      };
      if(this.map.getZoom() > '15'){
        this.siteLists.forEach((item, index) => {
          const marker = new google.maps.Marker({
            position: new google.maps.LatLng(item.latitude, item.longitude),
            title: item.stationname,
            icon: greenCircle,
            // icon: {
            //   url: require("../assets/images/busStop.png"),
            //   scaledSize: new google.maps.Size(30, 35),
            // },
            // image: imageStyle,
            map: this.map,
          });
          this.markers.push(marker);
          this.attachSecretMessage(marker, this.siteLists[index]);
        });
      }
      this.map.addListener("click", (event) => {
        event.stop();
      });
    },

    //地图相关操作(放大/缩小/复原)
    handleControl(name) {
      // let view = this.map.getView();
      switch (name) {
        case "enlarge":
          this.map.setZoom(this.map.getZoom() + 1);
          break;
        case "norrow":
          this.map.setZoom(this.map.getZoom() - 1);
          break;
        case "restore":
          this.map.setCenter({
            lat: this.$store.state.lnglat[1],
            lng: this.$store.state.lnglat[0],
          });
          this.map.setZoom(window.MAPSETTINGS.DEFAULTZOOM);
          break;
      }
    },
    // 站点图标点击事件
    attachSecretMessage(marker, secretMessage) {
      let that = this;
      marker.addListener("click", () => {
        let { stationname, rundirection, dualserialid, stationid, segmentid } =
          secretMessage;
        that.routeName = stationname;
        that.routeRundirection = rundirection;
        that.dualserialid = dualserialid;
        that.stationid = stationid;
        that.segmentid = segmentid;
        that.getStationRoute();
      });
    },
    // 获取选中站点的所有线路
    async getStationRoute() {
      clearInterval(this.setTime);
      let params = {
        stationId: this.stationid,
        userId: localStorage.getItem("userId")
          ? localStorage.getItem("userId")
          : "", //用户id
      };
      let { status, data } = await getStationRoute(params);
      if (status == 200) {
        this.collectDatas = data;
        this.isCollecData = true;
      }
    },
    // 关闭线路弹窗
    handleClose() {
      this.isShowRouteList = false;
      clearInterval(this.setTime);
    },
    // 点击弹窗线路信息-进入线路详情
    handleChangeRoute(item, index) {
      this.$store.commit("setRouteListStore", item);
      this.$router.push({
        name: "routeDetail",
        params: {
          routeName: this.routeName,
          stationid: this.stationid,
          index: index,
        },
      });
    },
  },
  destroyed() {
    clearInterval(this.setTime);
    Notification.closeAll();
    this.$store.commit("setIsNotifyShow", this.isNotifyShow);
  },
};
</script>
<style>
.notify-success::-webkit-scrollbar {
  width: 0px;
}
.el-notification{
  display: flex;
  width: 330px;
  height: 300px;
  padding: 14px 26px 14px 13px;
  border-radius: 8px;
  box-sizing: border-box;
  border: 1px solid #EBEEF5;
  position: fixed;
  background-color: #FFF;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  transition: opacity .3s,transform .3s,left .3s,right .3s,top .4s,bottom .3s;
  overflow: auto;
}
</style>
<style lang="scss" scoped>
.map {
  overflow: hidden;
  position: relative;
  #map {
    width: 100%;
  }
}

.refresh-station-box {
  position: fixed;
  z-index: 999;
  top: 161px;
  left: 8px;
  width: 36px;
  height: 36px;
  text-align: center;
  line-height: 36px;
  background: #fff;
  border: 1px solid #d9d9d9;
  color: #000;
  font-weight: 900;
}
::v-deep .ol-zoom-in,
::v-deep .ol-zoom-out {
  width: 36px;
  height: 36px;
}
// [class*=" el-icon-"],
// [class^="el-icon-"] {
//   font-size: 25px;
//   margin-bottom: 10px;
// }
</style>
